#include "msp_bkpr.h"
// 
#include <string.h>
// 
#include "stm32f1xx.h"
// #include "stm32f1xx_ll_rtc.h"
#include "stm32f1xx_ll_pwr.h"

#define BKPR_BUFFER_SIZE                    (BKPR_DR_NUMBER * 4)                    // 

//备份寄存器缓存区
uint8_t  bkpr_buffer[BKPR_BUFFER_SIZE];
uint32_t *p = (uint32_t *)bkpr_buffer;

//备份寄存器地址偏移表
uint32_t bkpr_addr_tab[BKPR_DR_NUMBER] =
{
    // TAMP_BKP0R, TAMP_BKP1R, TAMP_BKP2R, TAMP_BKP3R, TAMP_BKP4R
    0
};

//备份寄存器初始化
void Msp_Bkpr_Init(void)
{
    // crm_periph_clock_enable(CRM_PWC_PERIPH_CLOCK, TRUE);
    // crm_periph_clock_enable(CRM_BKPR_PERIPH_CLOCK, TRUE);
    // pwc_battery_powered_domain_access(TRUE);
    // bkpr_flag_clear(BKPR_TAMPER_EVENT_FLAG);
}

/**
 * @brief 
 * 
 * @param pdata 
 * @param len 
 */
uint8_t Msp_Bkpr_Write(uint8_t *pdata, uint8_t len)
{
    if(len > BKPR_BUFFER_SIZE)
        return BKPR_BUFFER_ERROR ;
    memcpy(bkpr_buffer, pdata, len);
    //同步数据到备份寄存器
    LL_PWR_EnableBkUpAccess();              //关闭写保护
    // for(uint8_t i = 0; i < BKPR_DR_NUMBER; i++)
        // LL_RTC_BKP_SetRegister(TAMP, bkpr_addr_tab[i], p[i]);
        // (*(uint32_t *)(0x4000B000 + 0x100 + i)) = p[i];
    LL_PWR_DisableBkUpAccess();             //打开写保护
    return BKPR_BUFFER_DONE;
}

/**
 * @brief 
 * 
 * @param pdata 
 * @param len 
 */
uint8_t Msp_Bkpr_Read(uint8_t *pdata, uint8_t len)
{
    if(len > BKPR_BUFFER_SIZE)
        return BKPR_BUFFER_ERROR;
    // LL_PWR_EnableBkUpAccess();              //关闭写保护
    // for(uint8_t i = 0; i < BKPR_DR_NUMBER; i++)
    //     p[i] = LL_RTC_BKP_GetRegister(TAMP, bkpr_addr_tab[i]);
    memcpy(pdata, bkpr_buffer, len);
    // LL_PWR_DisableBkUpAccess();             //打开写保护
    return BKPR_BUFFER_DONE;
}
